#include <stdio.h>
#include <iostream>
#include "gPTP/ptp.h"
#include "tsmp/tsmp.h"
#include "../../../../../../usr/include/netinet/in.h"
#include <unistd.h>
#include "config/writer.h"
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <cstring>
#include <cerrno>
#include <atomic>

// 创建一个TSNConfig结构体实例
TSNConfig config;
char *NET_INIT;
Tunnel *tunnel;
int if_master[MAX_PORT_NUM]; // 记录主端口号
int if_slave[MAX_PORT_NUM];  // 记录从端口号
int relay_flag = 0;
int sum_slave = 0;
int sum_master = 0;

int main(int argc, char *argv[])
{

    key_t key = ftok("config/netconf_mdfile/client_input.xml", 'a');
    if (key == -1)
    {
        perror("ftok");
        exit(EXIT_FAILURE);
    }

    // 获取共享内存段的 ID
    int shmid = shmget(key, 10000, 0666);
    if (shmid == -1)
    {
        perror("shmget");
        exit(EXIT_FAILURE);
    }

    // 将共享内存段附加到进程地址空间
    tunnel = static_cast<Tunnel *>(shmat(shmid, nullptr, 0));
    if (tunnel == reinterpret_cast<Tunnel *>(-1))
    {
        perror("shmat");
        exit(EXIT_FAILURE);
    }

    if (tunnel == nullptr)
    {
        std::cerr << "Shared memory not initialized\n";
        return 0;
    }

    // 使用原子操作检查 tag//更新--插入进OSS
    while (!tunnel->tag.load(std::memory_order_acquire))
        ;

    write_TSNConfig(&config, tunnel);
    printf("Configuration succeeded!\n");

    tunnel->tag.store(0, std::memory_order_acquire);

    if (argc < 2)
    {
        std::cout << "please give me more parameters" << std::endl;
        return 1;
    }
    else if (argc > 2)
    {
        std::cout << "The parameters are too much" << std::endl;
        return 1;
    }
    NET_INIT = argv[1];
    // 全局时钟置零
    uint32_t _init_local_clock[2] = {0, 0};
    writeReqSend(0x00080004, 2, _init_local_clock); // 全局时钟置零
    init_info_sync();
    init_info_pdelay();

    for (int i = 0; i <= MAX_PORT_NUM - 1; i++) // 读取主端口和从端口
    {
        if_master[i] = (config.master_port >> i) & 1;
        if_slave[i] = (config.slave_port >> i) & 1;
        sum_master += if_master[i];
        sum_slave += if_slave[i];
    }
    // 如果主从端口都不全为0，则是中继节点
    if (sum_master != 0 && sum_slave != 0)
    {
        relay_flag = 1;
    }

    for (int i = 0; i <= MAX_PORT_NUM - 1; i++) // 输出主端口
    {
        printf("if_master[%d]:%d\n", i, if_master[i]);
    }

    for (int i = 0; i <= MAX_PORT_NUM - 1; i++) // 输出从端口
    {
        printf("if_slave[%d]:%d\n", i, if_slave[i]);
    }

    if (config.gm_flag)
    {
        printf("----------------GM start------------------\n");
        timer_fun_sync(3);
    }
    else
    {
        printf("----------------Slave start------------------\n");
        uint32_t rale[1] = {htonl(0x00000001)};
        writeReqSend(0x40000000, 1, rale); // set slave_role_reg
    }

    timer_fun_pdelay(2);
    packRec(config.gm_flag);

    // 断开与共享内存段的连接
    if (shmdt(tunnel) == -1)
    {
        perror("shmdt");
        exit(EXIT_FAILURE);
    }

    return 0;
}